#!/usr/bin/env python
#coding:utf8
#author:Finy

import urllib2
import cookielib
import urllib
import re


class browser():
    def __init__(self, proxy_type='http', proxy=None, timeout=10):
        self.proxy = proxy
        self.proxy_type = proxy_type
        self.timeout = timeout
        self.urllib2 = urllib2
        self.header = [('User-agent',
                        'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)')]
        self.cj = cookielib.CookieJar()
        self.opener = urllib2.build_opener(
            urllib2.HTTPCookieProcessor(self.cj))
        self.opener.addheaders = self.header
        urllib2.install_opener(self.opener)

    def open(self, url, data=None):
        if url[0:7] != 'http://':
            url = 'http://' + url
        print url
        if data:
            postdata = urllib.urlencode(data)
            request = urllib2.Request(url, postdata)
        else:
            request = urllib2.Request(url)
        if self.proxy:
            request.set_proxy(self.proxy, self.proxy_type)
        try:
            fp = urllib2.urlopen(request, timeout=self.timeout)
            stat = True
        except Exception, HttpeError:
            stat = False
            fp = HttpeError
        return stat, fp


class search():
    def __init__(self, key, google='74.125.21.98'):
        self.key = key
        self.google = google
        self.par = '/search?hl=en&newwindow=1&q=%s&start=0&sa=N&num=30' % self.key

    def google_search(self):
        google_get_url = self.google + self.par
        b = browser()
        stat, fp = b.open(google_get_url)
        if stat:
            return fp.read()
        else:
            print 0
            return fp

    def result_geturl(self, fp):
        #com = re.compile(r'href\="(.*)" onmousedown\=')
        url = re.findall(r'href\="(.*)" onmousedown\=', fp)
        print url


class attack():
    pass

if __name__ == '__main__':
    #b = browser(proxy='172.16.1.1:8087')
    #b = browser()
    #stat, fp = b.open('209.85.225.104')
    g = search(key='inurl:faq.php+intext:7.2')
    fp = g.google_search()
    #print fp
    g.result_geturl(fp)
    #if stat:
    #    print fp.read()
    #else:
    #    print fp
